package com.wmh.baseservice.common.service;

import com.wmh.baseservice.common.shiro.jwt.JwtTokenUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenService {

    private final HttpServletRequest request;

    public TokenService(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 根据token获取用户id
     * @return 返回用户id
     */
    public Long getUserIdFromToken() {
        String jwt = request.getHeader("Authorization");
        jwt = jwt.replace("Bearer_", "");
        if (Boolean.FALSE.equals(JwtTokenUtil.isTokenExpired(jwt))) {
            throw new IllegalStateException("令牌过期或无效!");
        }
        return Long.parseLong(JwtTokenUtil.getUserInfoFromToken(jwt).get("usId").toString());
    }
}
